package com.jtpay.payresulthelper.hook;

import android.app.Activity;
import android.os.Bundle;
import com.jtpay.payresulthelper.util.LogUtil;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;

import static com.jtpay.payresulthelper.constant.HooKConstant.CLASS_LOGIN;
import static com.jtpay.payresulthelper.constant.HooKConstant.PACKAGE_NAME_ALIPAY;
import static com.jtpay.payresulthelper.util.ClassUtil.getClazz;

// hook important message from other app
public class HookManager implements IXposedHookLoadPackage {

    @Override
    public void handleLoadPackage(LoadPackageParam param) {
        if (null != param.appInfo && ((param.appInfo.flags & 129) == 0)) {
            aliPayHook(param);
        }
    }

    private void aliPayHook(final LoadPackageParam loadPackageParam) {
        if (PACKAGE_NAME_ALIPAY.equals(loadPackageParam.packageName)) {
            Class cls = getClazz(CLASS_LOGIN, loadPackageParam.classLoader);
            if (null != cls) {
                XposedHelpers.findAndHookMethod(cls, "onCreate", Bundle.class, new XC_MethodHook() {
                    protected void beforeHookedMethod(MethodHookParam arg6) {
                        try {
                            super.beforeHookedMethod(arg6);
                            Object activity = arg6.thisObject;
                            new AliPayHook(loadPackageParam.classLoader, (Activity) activity);
                        } catch (Throwable throwable) {
                            LogUtil.log("handleLoadPackage throwable reason " + throwable.getMessage());
                            throwable.printStackTrace();
                        }
                    }
                });
            }
        }
    }


}
